const express = require('express');
const db = require('../config/db');
const { authenticateToken } = require('../middleware/auth');
const router = express.Router();

// 获取流程列表
router.get('/processes', authenticateToken, async (req, res) => {
  try {
    const { page = 1, pageSize = 10, name, status } = req.query;
    const offset = (page - 1) * pageSize;
    
    // 构建查询条件
    let query = 'SELECT id, name, status, creator, created_at as createdAt, use_count as useCount, version FROM workflow_processes WHERE 1=1';
    let countQuery = 'SELECT COUNT(*) as total FROM workflow_processes WHERE 1=1';
    const params = [];
    
    if (name) {
      query += ' AND name LIKE ?';
      countQuery += ' AND name LIKE ?';
      params.push(`%${name}%`);
    }
    
    if (status) {
      query += ' AND status = ?';
      countQuery += ' AND status = ?';
      params.push(status);
    }
    
    query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
    params.push(parseInt(pageSize), parseInt(offset));
    
    const [rows] = await db.execute(query, params);
    const [countResult] = await db.execute(countQuery, params.slice(0, -2));
    const total = countResult[0].total;
    
    res.json({
      code: 200,
      message: '获取流程列表成功',
      data: {
        list: rows,
        pagination: {
          currentPage: parseInt(page),
          pageSize: parseInt(pageSize),
          total: total
        }
      }
    });
  } catch (error) {
    console.error('获取流程列表失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

// 创建新流程
router.post('/processes', authenticateToken, async (req, res) => {
  try {
    const { name, nodes, connections } = req.body;
    const userId = req.user.id;
    const userName = req.user.name;
    
    // 参数验证
    if (!name) {
      return res.status(400).json({
        code: 400,
        message: '流程名称不能为空'
      });
    }
    
    // 插入流程数据
    const [result] = await db.execute(
      'INSERT INTO workflow_processes (name, creator_id, creator, nodes, connections, version) VALUES (?, ?, ?, ?, ?, ?)',
      [name, userId, userName, JSON.stringify(nodes), JSON.stringify(connections), 'v1.0']
    );
    
    const processId = result.insertId;
    
    // 获取插入的流程详情
    const [rows] = await db.execute(
      'SELECT id, name, status, creator, created_at as createdAt, use_count as useCount, version FROM workflow_processes WHERE id = ?',
      [processId]
    );
    
    res.status(201).json({
      code: 201,
      message: '流程创建成功',
      data: rows[0]
    });
  } catch (error) {
    console.error('创建流程失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

// 获取流程详情
router.get('/processes/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    
    const [rows] = await db.execute(
      'SELECT * FROM workflow_processes WHERE id = ?',
      [id]
    );
    
    if (rows.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '流程不存在'
      });
    }
    
    const process = rows[0];
    // 解析JSON字段
    process.nodes = JSON.parse(process.nodes);
    process.connections = JSON.parse(process.connections);
    
    res.json({
      code: 200,
      message: '获取流程详情成功',
      data: process
    });
  } catch (error) {
    console.error('获取流程详情失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

// 更新流程
router.put('/processes/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const { name, nodes, connections, status } = req.body;
    
    // 参数验证
    if (!name) {
      return res.status(400).json({
        code: 400,
        message: '流程名称不能为空'
      });
    }
    
    // 更新流程数据
    const [result] = await db.execute(
      'UPDATE workflow_processes SET name = ?, nodes = ?, connections = ?, status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [name, JSON.stringify(nodes), JSON.stringify(connections), status || 'disabled', id]
    );
    
    if (result.affectedRows === 0) {
      return res.status(404).json({
        code: 404,
        message: '流程不存在'
      });
    }
    
    // 获取更新后的流程详情
    const [rows] = await db.execute(
      'SELECT id, name, status, creator, created_at as createdAt, use_count as useCount, version FROM workflow_processes WHERE id = ?',
      [id]
    );
    
    res.json({
      code: 200,
      message: '流程更新成功',
      data: rows[0]
    });
  } catch (error) {
    console.error('更新流程失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

// 删除流程
router.delete('/processes/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    
    // 删除流程
    const [result] = await db.execute(
      'DELETE FROM workflow_processes WHERE id = ?',
      [id]
    );
    
    if (result.affectedRows === 0) {
      return res.status(404).json({
        code: 404,
        message: '流程不存在'
      });
    }
    
    res.json({
      code: 200,
      message: '流程删除成功'
    });
  } catch (error) {
    console.error('删除流程失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

// 切换流程状态
router.put('/processes/:id/toggle', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    
    // 获取当前流程状态
    const [rows] = await db.execute(
      'SELECT status FROM workflow_processes WHERE id = ?',
      [id]
    );
    
    if (rows.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '流程不存在'
      });
    }
    
    const currentStatus = rows[0].status;
    const newStatus = currentStatus === 'enabled' ? 'disabled' : 'enabled';
    
    // 更新流程状态
    await db.execute(
      'UPDATE workflow_processes SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [newStatus, id]
    );
    
    res.json({
      code: 200,
      message: `流程${newStatus === 'enabled' ? '启用' : '禁用'}成功`,
      data: {
        status: newStatus
      }
    });
  } catch (error) {
    console.error('切换流程状态失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

// 获取流程实例列表
router.get('/processes/:id/instances', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const { page = 1, pageSize = 10 } = req.query;
    const offset = (page - 1) * pageSize;
    
    // 检查流程是否存在
    const [processRows] = await db.execute(
      'SELECT id FROM workflow_processes WHERE id = ?',
      [id]
    );
    
    if (processRows.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '流程不存在'
      });
    }
    
    // 获取流程实例列表
    const [rows] = await db.execute(
      'SELECT id, process_id, start_time as startTime, current_node as currentNode, assignee, status, duration FROM workflow_instances WHERE process_id = ? ORDER BY start_time DESC LIMIT ? OFFSET ?',
      [id, parseInt(pageSize), parseInt(offset)]
    );
    
    const [countResult] = await db.execute(
      'SELECT COUNT(*) as total FROM workflow_instances WHERE process_id = ?',
      [id]
    );
    const total = countResult[0].total;
    
    res.json({
      code: 200,
      message: '获取流程实例列表成功',
      data: {
        list: rows,
        pagination: {
          currentPage: parseInt(page),
          pageSize: parseInt(pageSize),
          total: total
        }
      }
    });
  } catch (error) {
    console.error('获取流程实例列表失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

// 获取阻塞节点列表
router.get('/blocked-nodes', authenticateToken, async (req, res) => {
  try {
    const { page = 1, pageSize = 10 } = req.query;
    const offset = (page - 1) * pageSize;
    
    // 获取阻塞节点列表
    const [rows] = await db.execute(
      'SELECT node_name as nodeName, process_name as processName, assignee, block_time as blockTime, duration FROM workflow_blocked_nodes ORDER BY block_time DESC LIMIT ? OFFSET ?',
      [parseInt(pageSize), parseInt(offset)]
    );
    
    const [countResult] = await db.execute(
      'SELECT COUNT(*) as total FROM workflow_blocked_nodes'
    );
    const total = countResult[0].total;
    
    res.json({
      code: 200,
      message: '获取阻塞节点列表成功',
      data: {
        list: rows,
        pagination: {
          currentPage: parseInt(page),
          pageSize: parseInt(pageSize),
          total: total
        }
      }
    });
  } catch (error) {
    console.error('获取阻塞节点列表失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

module.exports = router;